package com.itestor.iptv.modules.common.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import com.itestor.iptv.global.dao.GenericHibernateDao;
import com.itestor.iptv.modules.common.domain.RoleGroup;
import com.itestor.iptv.modules.common.domain.RoleGroupRobot;

/**
 * @author Mr.li
 */
public class TbRoleGroupDao extends GenericHibernateDao<RoleGroup, Integer> {

    /**
     * 查找权限组.
     * @param roleGroupName
     * @return RoleGroup
     */
    public RoleGroup find(String roleGroupName) {
        StringBuilder hql = new StringBuilder();
        hql.append("from RoleGroup t where t.roleGroupName=:roleGroupName");
        Query query = getHibernateSession().createQuery(hql.toString());
        query.setParameter("roleGroupName", roleGroupName);

        return getEntity(query);
    }

    /**
     * 创建聚合组.
     * @param pIdRoleGroup
     * @param pRobotId
     */
    public void mergeRoleGroupRobotRelation(int pIdRoleGroup, Integer pRobotId) {
        RoleGroupRobot relation = new RoleGroupRobot();
        relation.setIdRoleGroup(pIdRoleGroup);        
        relation.setIdRobot(pRobotId); 
        relation.setRoleLevel(RoleGroupRobot.ROLE_LEVEL_WRITE);
        
        Session session = getHibernateSession();
        session.saveOrUpdate(relation);
    }
    
    /**
     * 删除关联设备
     * @param idRoleGroup
     * @param idRobot
     */
    public void deleteRelRobot(int idRoleGroup, int idRobot) {
        StringBuilder hql = new StringBuilder();
        hql.append("delete from RoleGroupRobot t where t.idRoleGroup=:idRoleGroup and t.idRobot=:idRobot");
        Query query = getHibernateSession().createQuery(hql.toString());
        
        query.setParameter("idRoleGroup", idRoleGroup);
        query.setParameter("idRobot", idRobot);        
        query.executeUpdate();     
    }

    /**
     * 修改权限组关联设备的操作权限
     * @param roleGroupId
     * @param pRobotId
     * @param roleLevel
     */
    public void updateRelRobotRoleLevel(int roleGroupId, Integer pRobotId,
            int roleLevel) {
       
        StringBuilder hql = new StringBuilder();
        hql.append("update from RoleGroupRobot t  set t.roleLevel=:roleLevel  where t.idRoleGroup=:idRoleGroup and t.idRobot=:idRobot");
        Query query = getHibernateSession().createQuery(hql.toString());
        
        query.setParameter("idRoleGroup", roleGroupId);
        query.setParameter("idRobot", pRobotId);
        query.setParameter("roleLevel", roleLevel);   
        
        query.executeUpdate();   
        
    }
    
}